<?php

namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use App\Http\Model\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CategoryController extends Controller
{

    // 栏目页
    public function index()
    {
    	$list = Category::select('id','pid as pId','name')->get();

    	$this->data['catList'] = empty($list) ? '[]' : json_encode($list);
    	$this->data['nav'] = ['c'=>'category','a'=>'index'];
        return view('admin.category',$this->data);
    }

    // 栏目详情
    public function info(Request $request,$catid){
    	// $catid = intval($request->input('catid'));

    	if (empty($catid)) {
    		return response()->json(['status'=>false,'msg'=>'缺少必要参数']);
    	}

    	$data = Category::select('id','name')->where('id',$catid)->first();
    	return response()->json(['status'=>true,'data'=>$data]);
    }

    // 添加编辑栏目
    public function save(Request $request){
    	$catid = intval($request->input('catid'));
    	$name = $request->input('name');
    	$pid = $request->input('pid');

    	if (is_null($name) || $name == '') return response()->json(['status'=>false,'msg'=>'栏目名称不能为空']);
    	$data = ['name'=>$name];
    	if (!is_null($pid) && is_numeric($pid)) $data['pid'] = $pid;

    	if (empty($catid)) {  // 添加
    		$data['createtime'] = date('Y-m-d H:i:s',time());
    		$res = Category::select('id')->where('name',$data['name'])->first();
    		if (!empty($res)) return response()->json(['status'=>false,'msg'=>'栏目名称已经存在']);

    		$catid = Category::insertGetId($data);
    	}else {  // 编辑
    		$res = Category::select('id')->where('name',$data['name'])->first();
    		if (!empty($res['id']) && $res['id'] != $catid) return response()->json(['status'=>false,'msg'=>'栏目名称已经存在']);

    		$catid = Category::where('id',$catid)->update($data);
    	}

    	return response()->json(['status'=>true,'data'=>['id'=>$catid]]);
    }

    // 删除栏目
    public function del(Request $request,$catid){
    	if (empty($catid)) return response()->json(['status'=>false,'msg'=>'缺少必要参数']);

    	Category::where('id',$catid)->delete();

    	// 删除下级栏目
    	$list = Category::select('id')->where('pid',$catid)->get();
    	while (!empty($list)) {
    		$newList = [];
    		foreach ($list as $v) {
    			$res = Category::select('id')->where('pid',$v['id'])->get();
    			if (!empty($res)) $newList = array_merge($newList,$res);

    			Category::where('id',$v['id'])->delete();
    		}
    		$list = $newList;
    	}

    	return response()->json(['status'=>true]);
    }
}
